﻿function fixWidth(percent) {
    var bodyWidth = document.body.clientWidth;
    return (bodyWidth) * percent;
}
var isedit=false;
$(function() {
    $("#tr3").hide();
    $("#tr4").hide();
    dlg_Edit = $('#Dlg-Edit').dialog({
        closed: true,
        modal: true,
        toolbar: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: saveData
        }, '-', {
            text: '关闭',
            iconCls: 'icon-no',
            handler: function() {
                dlg_Edit.dialog('close');
            }
        }]
    });
    dlg_Edit_form = dlg_Edit.find('form');

    $('#btn-search,#btn-search-cancel').linkbutton();
    searchWin = $('#search-window').window({
        closed: true,
        modal: true,
        minimizable: false,
        maximizable: false,
        collapsible: false
    });

    $("#EmployeeName").bind("blur", function() {
        $("#TxtUserName").val(CC2PY($("#EmployeeName").val()));//得到用户名的拼音
    });
    searchForm = searchWin.find('form');

    autoResize({ dataGrid: '#grid', callback: InitList });

    $(document).keydown(function(e) {
        if (e.which == 13) {
            $("#btn-search").click();
        }
    });
});
//    $('body').layout();

function createColumnMenu() {
    var tmenu = $('<div id="tmenu" style="width:100px;"></div>').appendTo('body');
    var fields = grid.datagrid('getColumnFields');
    for (var i = 0; i < fields.length; i++) {
        $('<div iconCls="icon-ok"/>').html(fields[i]).appendTo(tmenu);
    }
    tmenu.menu({
        onClick: function (item) {
            if (item.iconCls == 'icon-ok') {
                grid.datagrid('hideColumn', item.text);
                tmenu.menu('setIcon', {
                    target: item.target,
                    iconCls: 'icon-empty'
                });
            } else {
                grid.datagrid('showColumn', item.text);
                tmenu.menu('setIcon', {
                    target: item.target,
                    iconCls: 'icon-ok'
                });
            }
        }
    });
}

function InitList(size) {
    var p = { AssemblyName: "OA.Bll.Authority", ClassName: "OA.Bll.Authority.UserInfoPresenter", Method: "GetUserRoleGroupList", Options: {} };
	grid = $('#grid').datagrid({
		title: '用户信息',
		iconCls: 'icon-save',
		methord: 'post',
		url: '../../Handler/AjaxHandle.ashx',
		queryParams: { "json": $.toJSON(p) },
		sortName: 'ID',
		sortOrder: 'desc',
		idField: 'ID',
		width: size.width,
		height: size.height,
		pageSize: Math.round(size.height / 25),
		pageList: [Math.round(size.height / 25)],
		columns: [[
			{ field: 'ID', title: 'ID', width:10, hidden: true },
			{ field: 'UserName', title: '用户名', width: 250 },
			{ field: 'RoleName', title: '用户角色', width: 250},
			{ field: 'GroupName', title: '用户组', width: 250 },
			{ field: 'CreateTime', title: '注册时间', width: 250 },
			{ field: 'Password', title: '密码', width: 10, hidden: true }
		]],
		pagination: true,
		rownumbers: true,
		singleSelect: true,
		toolbar: [{
			text: '新增',
			iconCls: 'icon-add',
			handler: add
		}, '-', {
			text: '修改',
			iconCls: 'icon-edit',
			handler: edit
		}, '-', {
			text: '删除',
			iconCls: 'icon-remove',
			handler: del
		}, '-', {
			text: '查找',
			iconCls: 'icon-search',
			handler: OpensearchWin
		}],
		onHeaderContextMenu: function(e, field) {
			e.preventDefault();
			if (!$('#tmenu').length) {
				createColumnMenu();
			}
			$('#tmenu').menu('show', {
				left: e.pageX,
				top: e.pageY
			});
		}
	});
}

var tree;
var grid;
var dlg_Edit;
var dlg_Edit_form;
var searchWin;
var searchForm;
var isedit=false;
var row;


function getSelectedArr() {
    var ids = [];
    var rows = grid.datagrid('getSelections');
	row = rows[0];
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].ID);
    }
    return ids;
}
function getSelectedID() {
    var ids = getSelectedArr();
    return ids.join(',');
}
function arr2str(arr) {
    return arr.join(',');
}
 var rows ;
 var operate;
function add() {
    show("注册新用户");
       $("#tr1").show();
       $("#tr2").show();
       $("#trEmployeeName").show();
       $("#trDeptName").show();
       $("#tr3").hide();
       $("#tr4").hide();
//    $("#TxtUserName").unbind("focus");
    dlg_Edit.dialog('open');
    dlg_Edit_form.form('clear');
     operate="add";
//    dlg_Edit_form.url = 'Handler/UserManageHandler.ashx?action=add';

}
function show(mytitle)
{
	$("#Dlg-Edit").dialog({
		title: mytitle
	});
}
function edit() {

    rows = grid.datagrid('getSelections');
    var num = rows.length;
    if (num == 0) {
        Msgslide('请选择一条记录进行操作!'); //$.messager.alert('提示', '请选择一条记录进行操作!', 'info');
        return;
    }
    else if (num > 1) {
        Msgfade('您选择了多条记录,只能选择一条记录进行修改!'); //$.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info');
        return;
    }
    else {
//        $("#txtUsername").val(rows[0].UserName);
//        $("#txtOldPassword").val(rows[0].Password);
        show("修改用户密码");
        isedit =true;
        row =rows [0];
        $("#tr3").show();
        $("#tr4").show();
       $("#tr1").hide();
       $("#tr2").hide();
       $("#trEmployeeName").hide();
       $("#trDeptName").hide();
        dlg_Edit.dialog('open');
        operate="edit";
  }
}
function del() {
    var arr = getSelectedArr();
	
    if (arr.length > 0) {
    	if(row.UserName=="admin") {
		$.messager.alert("信息提示", "此用户禁止删除", "info");
		return;
	}
        $.messager.confirm('提示信息', '您确认要删除吗?', function (data) {
            if (data) {
                var p = { AssemblyName: "OA.Bll.Authority", ClassName: "OA.Bll.Authority.UserInfoPresenter", Method: "Delete", Options: {} };
                p.Options["Id"] = arr2str(arr);
                $.ajax({
                    url: '../../Handler/AjaxHandle.ashx' ,
                    type: 'post',
                    dataType: 'json',
                    data:$.toJSON(p),
                    success: function (r) {
                        if (r.flag) {
//                        	InitList();
                        	grid.datagrid('reload');
                        } else {
                            $.messager.alert('错误',r .msg , 'error');
                        }
                    },
                 error: function (r) {
                    $.messager.alert("信息提示", r.msg, "error");
                  }
                });
            }
        });
    } else {
        Msgshow('请先选择要删除的记录。');
    }
}

function Msgshow(msg) {
	$.messager.alert('提示', msg, 'info');
}

function Msgslide(msg) {
    $.messager.show({
        title: '提示',
        msg: msg,
        timeout: 3000,
        showType: 'slide'
    });
}
function Msgfade(msg) {
    $.messager.show({
        title: '提示',
        msg: msg,
        timeout: 3000,
        showType: 'fade'
    });
}

function OpensearchWin() {
    searchWin.window('open');
    searchForm.form('clear');
}

function saveData() {
    var param = { AssemblyName: "OA.Bll.Authority", ClassName: "OA.Bll.Authority.UserInfoPresenter", Method: "", Options: {} };
    if (operate == "edit") {
        param.Method = "Update";
        if ($("#txtNewPassword").val().length < 5 || $("#txtNewPassword").val().length > 20) {
            $.messager.alert('提示', '密码要求5到20位字符！', 'info');
            return;
        }
        if ($("#txtNewPassword").val() != $("#txtPassword").val()) {
            $.messager.alert('提示', '两次密码不一致!', 'info');
            $("#txtNewPassword").focus();
            return;
        }
        param.Options["UserName"] = row.UserName;
        param.Options["Password"] = $("#txtPassword").val();
    }
    else {
        param.Method = "Add";
        param.Options["DeptId"] = $("#DeptName").combobox("getValue");
        param.Options["DeptName"] = $("#DeptName").combobox("getText");
        param.Options["EmployeeName"] = $("#EmployeeName").val();
        param.Options["UserName"] = $("#TxtUserName").val();
        param.Options["Password"] = $("#txtOldPassword").val();
        if ($("#txtOldPassword").val().length < 5 || $("#txtOldPassword").val().length > 20) {
            $.messager.alert('提示', '密码要求5到20位字符！', 'info');
            return;
        }
    }
    if (dlg_Edit_form.form('validate')) {
           $.ajax({
            type: "post",
            url: '../../Handler/AjaxHandle.ashx',
            data: $.toJSON(param),
            dataType: 'json',
            success: function (data) {
                 if (data.flag) {
                grid.datagrid('reload');
                dlg_Edit.dialog('close');
                } else {
                    $.messager.alert('错误', data.msg, 'error');
                        }
            },
            error: function (data) {
             alert (data);
             alert (data.flag);
                 $.messager.alert("信息提示", data.msg, "error");
                }
        });
//    dlg_Edit_form.form('submit', {
//        type: "post",
//        url: 'Handler/AjaxHandle.ashx', 
//        data:{"json":$.toJSON(param)},
//        datatype:"json",
//        onSubmit: function () {
//            return $(this).form('validate');
//        },
//        success: function (data) {
//            if (data.flag) {
//                grid.datagrid('reload');
//                dlg_Edit.dialog('close');
//            } else {
//                $.messager.alert('错误', data.msg, 'error');
//            }
//        },
//       error: function (r) {
//                $.messager.alert("信息提示", "执行错误", "error");
//            }
//    });
        }
}

function SearchOK() {
    var sTitle = $("#txtSearchUsername").val();
    var p = { AssemblyName: "OA.Bll.Authority", ClassName: "OA.Bll.Authority.UserInfoPresenter", Method: "GetUserRoleGroupList", Options: {} };
    p.Options["Username"] = sTitle;
    searchWin.window('close');
    grid.datagrid({ 
        methord: 'post',
        url: 'Handler/AjaxHandle.ashx', 
        queryParams:{ "json": $.toJSON(p)}
    });
    grid.datagrid('reload');
}
function closeSearchWindow() {
    searchWin.window('close');
}